package com.github.h4de5ing.kmp.rtk

import java.io.Closeable
import java.io.File
import java.io.InputStream
import java.text.SimpleDateFormat
import java.util.*
import kotlin.properties.Delegates

/**
 * 字符串转数组
 * 输入: 000102030405060708
 * @return 返回 {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08}
 */
fun String.hexToByteArray(): ByteArray {
    var hex = replace(" ", "")
    if (hex.length % 2 != 0) hex = "0${hex}"
    val result = ByteArray(hex.length / 2)
    for (i in result.indices) {
        val index = i * 2
        val hexByte = hex.substring(index, index + 2)
        result[i] = hexByte.toInt(16).toByte()
    }
    return result
}

/**
 * 数组打印
 * @param {0x01,0x02,0x03}
 * @return 01 02 03
 */
fun ByteArray.toHexString(): String = this.toHexString(this.size)
fun ByteArray.toHexString(length: Int): String {
    val sb = StringBuilder()
    val hex = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F')
    for (i in 0 until length) {
        val value: Int = this[i].toInt() and 0xff
        sb.append(hex[value / 16]).append(hex[value % 16]).append(" ")
    }
    return sb.toString()
}

fun toByteArray(hexString: String): ByteArray {
    val data2 = hexString.replace(" ", "")
    val bytes = ByteArray(data2.length / 2)
    for (i in 0 until data2.length / 2) {
        val index = i * 2
        val tem = data2.substring(index, index + 2)
        bytes[i] = tem.toByte(16)
    }
    return bytes
}

fun closeIO(vararg closeables: Closeable?) {
    for (cb in closeables) {
        try {
            if (null == cb) continue
            cb.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}

fun now(): String = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date(System.currentTimeMillis()))

fun InputStream.is2File(file: File) = file.outputStream().use { it.write(readBytes()) }
interface Change {
    fun change(message: ByteArray)
}

interface ChangeBoolean {
    fun change(message: Boolean)
}


private var changeStringUI: Change? = null
var changUIString: ByteArray by Delegates.observable(byteArrayOf()) { _, _, new ->
    changeStringUI?.change(new)
}

fun setChangeUIString(onChange: ((ByteArray) -> Unit)) {
    changeStringUI = object : Change {
        override fun change(message: ByteArray) {
            onChange(message)
        }
    }
}

private var changeBoolean: ChangeBoolean? = null
var extIsRadioConfig: Boolean by Delegates.observable(false) { _, _, new ->
    changeBoolean?.change(new)
}

fun setConfigChange(onChange: (Boolean) -> Unit) {
    changeBoolean = object : ChangeBoolean {
        override fun change(message: Boolean) {
            onChange(message)
        }
    }
}

var radioUartName = ""

//操作系统 os.name [windows 11,mac os x,linux]
fun os() = System.getProperty("os.name").lowercase(Locale.getDefault())

//指令集 os.arch [amd64,x86_64,osaarch64]
fun osArch() = System.getProperty("os.arch").lowercase(Locale.getDefault())
